using UnityEngine;

namespace JufGame
{
    /// <summary>
    /// 脚本单例
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        [SerializeField] protected bool isDontDestroyOnLoad = false;
        public static T Instance
        {
            get
            {
                if(instance == null)
                {
                    instance = FindObjectOfType<T>();
                    if(instance == null)
                    {
                        new GameObject("Single_" + typeof(T)).AddComponent<T>();
                    }
                    else
                    {
                        instance.Init();
                    }
                }
                return instance;
            }
        }
        private static T instance;
        private void Awake()
        {
            if (instance == null)
            {
                instance = this as T;
                Init();
                if (isDontDestroyOnLoad)
                {
                    DontDestroyOnLoad(gameObject);
                }
            }
            else if (instance != this)
            {
                Destroy(gameObject);
            }

        }
        public virtual void Init(){; }
    }    
}

